package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetMealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 套餐管理
 */
/*@RestController
@RequestMapping("/setmeal")
@Slf4j*/
/*
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CategoryService categoryService;


    @PostMapping
    @CacheEvict(value="setMealCache",key="#setmeal.categoryId+'_'+#setmeal.status")
    public R<String> save(@RequestBody SetMealDto setMealDto){
        //打印数据
        log.info("套餐信息:{}",setMealDto);
        //调用业务层 保存套餐以及菜品功能
        setmealService.saveWithDish(setMealDto);
        return R.success("新增套餐成功");
    }
    //套餐分页查询
    @GetMapping("/page")
    //http://localhost:8080/setmeal/page?page=1&pageSize=10
    //# 套餐分页查询  sql如何实现
    //SELECT * FROM setmeal WHERE NAME LIKE '%xx%' ORDER BY update_time DESC LIMIT 0 ,10
    public R<Page> page(int page,int pageSize,String name){
        //分页构造器对象
        Page<Setmeal> pageInfo=new Page<>(page,pageSize);
        //创建Page对象,内部封装的是SetmealDto(categoryName)
        Page<SetMealDto> pageInfo02=new Page<>();
        //创建lambda构造器
        LambdaQueryWrapper<Setmeal> lqw=new LambdaQueryWrapper<>();
        //添加查询条件，根据name进行like模糊查询
        lqw.like(name!=null,Setmeal::getName,name);
        //添加排序条件，根据更新时间降序排列
        lqw.orderByDesc(Setmeal::getUpdateTime);
        //执行查询  select * from setmeal where name like '%儿童%' ORDER BY update_time DESC  limit 0 , 10
        //pageInfo:{total:4,records[{setmeal},{setmeal},{setmeal},{setmeal}],currentPage:1,pageSize:10}
        setmealService.page(pageInfo,lqw);


        //将pageInfo的数据组装到新的page对象上
        BeanUtils.copyProperties(pageInfo,pageInfo02,"records");
        //pageInfo02{currentPage:1,pageSize:10,total:4,records:[]}
        List<Setmeal> records=pageInfo.getRecords();

        */
/*//*
/获取pageInfo集合,遍历,重新创建SetmealDto,加入新的集合
        List<Setmeal> records = pageInfo.getRecords();
        for (Setmeal record : records) {
            SetMealDto setMealDto=new SetMealDto();
            // 将SetMeal所有属性复制到setMealDto上  没有分类名称
            BeanUtils.copyProperties(record,setMealDto);
            //setmeal所在分类ID
            Long categoryId = record.getCategoryId();
            //根据setmeal所在分类ID查询分类信息
            Category category = categoryService.getById(categoryId);
            if(category!=null){
                //为setMealDto赋值分类名称
                setMealDto.setCategoryName(category.getName());
            }
            list.add(setMealDto);
        }
        pageInfo02.setRecords(list); //1 10 4  4个对象[setmealDto]
        //进行响应
        //return R.success(pageInfo);
        return R.success(pageInfo02);*//*



        //stream操作：获取流,操作处理流,结束流
        //records.stream():获取流
        //records.stream().map();遍历其中数据
        //collect(Collectors.ToList());:将处理完的结果收集在一个集合中,结束流式操作
        //以下是流式处理的框架
        // records.stream().map().collect(Collectors.ToList());
        // records.stream().map( ()->{}     ).collect(Collectors.ToList());
        // records.stream().map( (item)->{}     ).collect(Collectors.ToList());  //此时item代表records中的每一个元素对象Setmeal对象  {}中遍历过程执行的动作
        List<SetMealDto> list = records.stream().map((item) -> {
            SetMealDto setmealDto = new SetMealDto();
            //对象拷贝
            BeanUtils.copyProperties(item,setmealDto);
            //分类id
            Long categoryId = item.getCategoryId();
            //根据分类id查询分类对象
            Category category = categoryService.getById(categoryId);
            if(category != null){
                //分类名称
                String categoryName = category.getName();
                setmealDto.setCategoryName(categoryName);
            }
            return setmealDto;
        }).collect(Collectors.toList());
        //list集合中存的是一个个的setMealDto对象,这些对象上是有分类名称的
        pageInfo02.setRecords(list);
        return R.success(pageInfo02);


    }

    //DELETE http://localhost:8080/setmeal?ids=1599232782664888322,1586616156652236802
    @DeleteMapping
    @CacheEvict(value="setMealCache",key="#setmeal.categoryId+'_'+#setmeal.status")
    public R<String> delete(@RequestParam List<Long> ids){
        //打印ids
        log.info(ids.toString());
        //调用业务层删除套餐功能
        setmealService.removeWithDish(ids);
        //返回结果
        return R.success("套餐删除成功");
    }


    //http://localhost:8080/setmeal/list?categoryId=1586538755675013121&status=1
    //SELECT * FROM setmeal WHERE category_id='1413386191767674881' AND STATUS=1
    @GetMapping("/list")
    @Cacheable(value="setMealCache",key="#setmeal.categoryId+'_'+#setmeal.status")
    public R<List<Setmeal>> list(Setmeal setmeal){
        LambdaQueryWrapper<Setmeal> lqw=new LambdaQueryWrapper<>();
        lqw.eq(setmeal.getCategoryId()!=null,Setmeal::getCategoryId,setmeal.getCategoryId());//WHERE category_id='1413386191767674881'
        lqw.eq(setmeal.getStatus()!=null,Setmeal::getStatus,setmeal.getStatus()); //AND STATUS=1
        lqw.orderByDesc(Setmeal::getUpdateTime);
        List<Setmeal> list=setmealService.list(lqw);
        return R.success(list);
    }
}
*/
@RestController
@RequestMapping("/setmeal")
@Slf4j
@Api(tags = "套餐相关接口")
public class SetmealController {

    @Autowired
    private SetmealService setmealService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 新增套餐
     * @param setmealDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    @ApiOperation(value = "新增套餐接口")
    public R<String> save(@RequestBody SetMealDto setmealDto){
        log.info("套餐信息：{}",setmealDto);

        setmealService.saveWithDish(setmealDto);

        return R.success("新增套餐成功");
    }

    /**
     * 套餐分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    @ApiOperation(value = "套餐分页查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value = "页码",required = true),
            @ApiImplicitParam(name = "pageSize",value = "每页记录数",required = true),
            @ApiImplicitParam(name = "name",value = "套餐名称",required = false)
    })

    public R<Page> page(int page,int pageSize,String name){
        //分页构造器对象
        Page<Setmeal> pageInfo = new Page<>(page,pageSize);
        Page<SetMealDto> dtoPage = new Page<>();

        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件，根据name进行like模糊查询
        queryWrapper.like(name != null,Setmeal::getName,name);
        //添加排序条件，根据更新时间降序排列
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);

        setmealService.page(pageInfo,queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo,dtoPage,"records");
        List<Setmeal> records = pageInfo.getRecords();

        List<SetMealDto> list = records.stream().map((item) -> {
            SetMealDto setmealDto = new SetMealDto();
            //对象拷贝
            BeanUtils.copyProperties(item,setmealDto);
            //分类id
            Long categoryId = item.getCategoryId();
            //根据分类id查询分类对象
            Category category = categoryService.getById(categoryId);
            if(category != null){
                //分类名称
                String categoryName = category.getName();
                setmealDto.setCategoryName(categoryName);
            }
            return setmealDto;
        }).collect(Collectors.toList());

        dtoPage.setRecords(list);
        return R.success(dtoPage);
    }

    /**
     * 删除套餐
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    @ApiOperation(value = "套餐删除接口")
    public R<String> delete(@RequestParam List<Long> ids){
        log.info("ids:{}",ids);

        setmealService.removeWithDish(ids);

        return R.success("套餐数据删除成功");
    }

    /**
     * 根据条件查询套餐数据
     * @param setmeal
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId + '_' + #setmeal.status")
    @ApiOperation(value = "套餐条件查询接口")
    public R<List<Setmeal>> list(Setmeal setmeal){
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(setmeal.getCategoryId() != null,Setmeal::getCategoryId,setmeal.getCategoryId());
        queryWrapper.eq(setmeal.getStatus() != null,Setmeal::getStatus,setmeal.getStatus());
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);

        List<Setmeal> list = setmealService.list(queryWrapper);

        return R.success(list);
    }
}












